package com.wxxymakers.grademark.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxxymakers.grademark.utils.RandomVerify;
import com.wxxymakers.grademark.utils.RestResponse;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @AUTHOR soft
 * @DATE 2018/12/23 18:36
 * @DESCRIBE 验证码拦截器 指定某些需要进行验证码验证的地址 即可验证
 */
public class VerifyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String code = (String) request.getSession().getAttribute(RandomVerify.S_KEY);

        String userCode = request.getParameter("code");

        if (StringUtils.isEmpty(userCode) || !userCode.equalsIgnoreCase(code)) {
            ObjectMapper mapper = new ObjectMapper();
            String value = mapper.writeValueAsString(RestResponse.fail("验证码错误！"));
            response.setCharacterEncoding("utf-8");
            response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
            response.getWriter().append(value);
            return false;
        }

        return true;
    }
}
